<template>
  <div>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
      <el-form-item label="SKU类型" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio value="text">文字</el-radio>
          <el-radio value="img">图片</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品规格" prop="sku">
        <div class="" style="width: 100%">
          <div class="skuBox" v-if="formData.sku.length > 0">
            <div v-for="(item,index) in formData.sku" class="skuItem">
              <div style="padding: 10px;background-color: #f7f8fa">
                <el-form-item  label-width="0"  style="margin-bottom: 0" :prop="'sku.'+index + '.name'" :rules="skuNameformRule">
                  <el-input v-model.trim="item.name" placeholder="规格标题" style="width: 200px" @change="updateSkuList"/>
                  <span style="margin: 0 15px">限制输入四个字符</span>
                  <el-button type="danger" link @click="delSku(index)">[移除]</el-button>
                </el-form-item>
              </div>
              <el-form-item label-width="0" style="margin-top: 10px" :prop="'sku.'+index + '.values'" :rules="skuValuesformRule">
                <div class="flexs" style="width: 100%;">
                  <div class="" style="flex: 1">
                    <el-input-tag size="large" v-model="item.values" draggable placeholder="规格名称" @change="skuItemValuesChange($event,index)" tag-type="success"/>
                  </div>
                  <div style="margin-left: 10px">按Enter回车键添加输入内容为标签，拖动标签调整顺序</div>
                </div>
              </el-form-item>
            </div>
          </div>
          <el-button @click="addSku" :icon="Plus">添加</el-button>
          <el-button @click="updateSkuList">刷新规格设置</el-button>
          <span style="margin: 0 15px;color: #f3262a">完成好商品规格后，请点击【刷新规格设置】</span>
        </div>
      </el-form-item>

      <el-form-item label="规格设置" prop="skuSetting">
        <div style="width: 100%">
          <el-table style="margin-bottom: 10px" v-loading="skuLoading" :data="skuList" :header-cell-style="{ background: '#F5F7FA' }"
                    element-loading-background="rgba(255, 255, 255, 0.6)" @selection-change="handleAllSelected">
            <el-table-column type="selection" width="55" />
            <template v-for="(v,i) in skuNames">
              <el-table-column :prop=" `skuName${i}`" :label="v"  width="100">
                <template #default="{ row }">
                  <span>{{row[`skuName${i}`]}}</span>
                </template>
              </el-table-column>
            </template>
            <el-table-column prop="sc_price" label="市场价">
              <template #default="{ row }">
                <div class="flexs">
                  <el-input v-model="formData.skuSetting[row.id].sc_price" placeholder=""/>
                  <span style="margin-left: 6px">元</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="ls_price" label="零售价">
              <template #default="{ row }">
                <div class="flexs">
                  <el-input v-model="formData.skuSetting[row.id].ls_price" placeholder=""/>
                  <span style="margin-left: 6px">元</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="gh_price" label="供货价">
              <template #default="{ row }">
                <div class="flexs">
                  <el-input v-model="formData.skuSetting[row.id].gh_price" placeholder=""/>
                  <span style="margin-left: 6px">元</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="cb_price" label="成本价">
              <template #default="{ row }">
                <div class="flexs">
                  <el-input v-model="formData.skuSetting[row.id].cb_price" placeholder=""/>
                  <span style="margin-left: 6px">元</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="kuchun" label="库存">
              <template #default="{ row }">
                <div class="flexs">
                  <el-input v-model="formData.skuSetting[row.id].kuchun" placeholder=""/>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="sales" label="销量">
              <template #default="{ row }">
                <div class="flexs">
                  <el-input v-model="formData.skuSetting[row.id].sales" placeholder=""/>
                  <span style="margin-left: 6px">kg</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="sales" label="利润率">
              <template #default="{ row }">

              </template>
            </el-table-column>
            <el-table-column prop="sales" label="设置会员价">
              <template #default="{ row }">

              </template>
            </el-table-column>
            <el-table-column prop="sales" label="订货商价">
              <template #default="{ row }">

              </template>
            </el-table-column>
          </el-table>
          <div>
            <el-button @click="">批量设置库存</el-button>
            <el-button @click="">批量设置价格</el-button>
          </div>
        </div>

      </el-form-item>
    </el-form>
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, shallowRef, reactive, onBeforeUnmount } from "vue"
import { useRouter } from "vue-router"
import { Plus } from "@element-plus/icons-vue"
const router = useRouter()
const { proxy } = getCurrentInstance()

const validSkuName = (rule, value, callback) => {
  if (value.length > 4) {
    callback(new Error("限制输入四个字符"))
  } else {
    callback()
  }
}
const skuNameformRule = [
  {required: true, message: "请输入规格标题", trigger: "blur"},
  {validator:validSkuName,trigger: "blur"}
];
const validSkuValues = (rule, value, callback) => {
  function hasDuplicate(arr) {
    return arr.length !== new Set(arr).size;
  }
  if (value === "" || value.length == 0) {
    callback(new Error("请输入规格名称"))
  } else if(hasDuplicate(value)) {
    callback(new Error("规格名称不得重复"))
  }else{
    callback()
  }
}
const skuValuesformRule = [
  // {required: true, message: "请输入规格名称", trigger: "blur"},
  {validator:validSkuValues,trigger: "change"}
]
const formRef = ref(null)
const formData = reactive({
  type:'text',
  sku:[],
  skuSetting:{}
});
formData.sku = reactive([
  { name: '颜色', values: ['红', '绿', '蓝'] },
  { name: '尺码', values: ['小', '中', '大'] }
])
formData.skuSetting = reactive({})
const formRules = reactive({});
const formLoading = ref(false);

const skuList = ref([]);
const skuNames = ref([])
const skuLoading = ref(false);

const addSku = () =>{
  formData.sku.push({
    name:'',
    values:[]
  })
}
const delSku = (i) =>{
  formData.sku.splice(i, 1);
  updateSkuList();
}
const skuItemValuesChange = (e,i) =>{
  // console.log("skuItemValueChange", e);
  // console.log("skuItemValueChange", i);
  updateSkuList();
}


function generateSKU(properties) {
  let skus = [];
  function generateCombinations(index, combination) {
    if (index >= properties.length) {
      skus.push(combination.join('||'));
    } else {
      properties[index].values.forEach(value => {
        generateCombinations(index + 1, [...combination, value]);
      });
    }
  }
  generateCombinations(0, []);
  return skus;
}
const updateSkuList = () =>{
  formRef.value.validate((valid, fields) => {
    if (!valid) {
      return;
    }
    const properties = JSON.parse(JSON.stringify(formData.sku)).filter(item => item.values.length>0);
    const _skus = generateSKU(properties);
    skuNames.value = properties.map(v=>v.name);
    skuList.value = []
    _skus.forEach((item,index) => {
      let data = {
        id:item
      }
      let _names = item.split('||');
      _names.forEach((v,i) => {
        data[`skuName${i}`] = v
      })
      skuList.value.push(data);
      if(!formData.skuSetting[data.id]){
        formData.skuSetting[data.id] = {};
      }
    })
  })
}

function handleAllSelected() {


}


onMounted(() => {
  // getClass()
  updateSkuList();
})
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {

})

</script>
<script>
export default {
  name: "sku",
}
</script>

<style lang="less" scoped>
.skuBox{
  border: 1px solid var(--el-border-color-light);
  padding: 10px;
  margin-bottom: 15px;
  .skuItem{
    margin-bottom: 10px;
  }
  .skuItem:last-child{
    margin-bottom: 0;
  }
}

</style>
